﻿namespace Licens.Class
{
    using Microsoft.Win32;
    using System;
    using System.Data;
    using System.IO;
    using System.Security.Cryptography;
    using System.Text;
    using System.Windows.Forms;

    public class Access
    {
        string _mespass = "caovu";
        int _idchuongtrinh = 1;
        
        //private string sfilenamekey = @"\systems.xml";
        //private string sfilePath = @"C:\Windows\System32";

        string _fileNameKey = "Systems";
        string _fileNameKeyds = "Sytems";
        string _pathFileKey = Directory.GetCurrentDirectory()+"\\";
        Keys _key;
        string _keystring = "";
        string _idcomputer = "";
        public string pKeyString
        {
            set 
            {
                if (value != "") _key = new Keys(value);
                else _key = new Keys();
            }
        }
        public Access()
        {
            khoitao();
            
        }
        public Access(int idchuongtrinh)
        {
            
            _idchuongtrinh = idchuongtrinh;
            khoitao();
        }
        void khoitao()
        {
            _idcomputer = SystemInfo.GetHDDSerialNumber();
        }
        public string DecryptString(string Message, string Passphrase)
        {
            byte[] buffer;
            UTF8Encoding encoding = new UTF8Encoding();
            MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider();
            byte[] buffer2 = provider.ComputeHash(encoding.GetBytes(Passphrase));
            TripleDESCryptoServiceProvider provider2 = new TripleDESCryptoServiceProvider {
                Key = buffer2,
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            };
            byte[] inputBuffer = Convert.FromBase64String(Message);
            try
            {
                buffer = provider2.CreateDecryptor().TransformFinalBlock(inputBuffer, 0, inputBuffer.Length);
            }
            finally
            {
                provider2.Clear();
                provider.Clear();
            }
            return encoding.GetString(buffer);
        }

        public string EncryptString(string Message, string Passphrase)
        {
            byte[] buffer;
            UTF8Encoding encoding = new UTF8Encoding();
            MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider();
            byte[] buffer2 = provider.ComputeHash(encoding.GetBytes(Passphrase));
            TripleDESCryptoServiceProvider provider2 = new TripleDESCryptoServiceProvider {
                Key = buffer2,
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            };
            byte[] bytes = encoding.GetBytes(Message);
            try
            {
                buffer = provider2.CreateEncryptor().TransformFinalBlock(bytes, 0, bytes.Length);
            }
            finally
            {
                provider2.Clear();
                provider.Clear();
            }
            return Convert.ToBase64String(buffer);
        }

        private RegistryKey f_checkRegist()
        {
            try
            {
                //this.sfilePath = Registry.LocalMachine.Name + @"\system\cvf\s1";
                RegistryKey key = Registry.LocalMachine.OpenSubKey("system", true);
                if (key == null)
                {
                    key = Registry.LocalMachine.CreateSubKey("system");
                    key = key.OpenSubKey(key.Name, true);
                }
                if (key.OpenSubKey("cvf", true) == null)
                {
                    key = Registry.LocalMachine.OpenSubKey("system", true).CreateSubKey("cvf");
                }
                if (key.OpenSubKey("s1", true) == null)
                {
                    key = Registry.LocalMachine.OpenSubKey("system", true).OpenSubKey("cvf", true).CreateSubKey("s1");
                }
                return key;
            }
            catch
            {
                return null;
            }
        }
        
        public string f_get_capkey(int songay, string ngaybd, bool vinhvien)
        {
            string maso = this.f_get_capmaso();
            return this.f_get_capkey(maso, songay, ngaybd, vinhvien);
        }

        public string f_get_capkey(string maso, int songay, string ngaybd, bool vinhvien)
        {
            string vlicens = "";
            if (vinhvien)
            {
                songay = 999;
            }
            Keys vkey = new Keys();
            vkey.pNgayBatDauSuDung = ngaybd;
            vkey.pSoNgaySuDung = songay;
            vkey.pIDChuongTrinh = _idchuongtrinh;
            vlicens = vkey.f_CreateKey();
            return vlicens;
        }

       
        public string f_get_capmaso()
        {
            string sfinal = "";
            Keys vkey = new Keys();
            vkey.pIDChuongTrinh = _idchuongtrinh;
            
            sfinal = vkey.f_CreateCodeNumber();
            return sfinal;
        }

        public bool f_kiemtra_maso(string maso)
        {
            if (!_key.f_CheckCodeNumber(maso, _idchuongtrinh)) return false;
            
            return true;
        }
        public bool f_kiemtra_madangky(Keys ckey)
        {
            if (ckey.pIDChuongTrinh == 0 || ckey.pKiTuBatDau == "" || ckey.pLanThu == 0 
                || ckey.pNgayBatDauSuDung == "" || ckey.pSoNgaySuDung == 0 || ckey.pSTT == 0)
            {
               return false;
            }
            
            return true;

        }

        public bool f_kiemtra_thoihan(Keys ckey)
        {
            
            int num = 0;
            try
            {
                num = ckey.pSoNgaySuDung;
            }
            catch
            {
            }
            if (num == 999)
            {
                return true;
            }
            DateTime now = DateTime.Now;
            try
            {
                string vsngaybd = ckey.pNgayBatDauSuDung;
                now = new DateTime(int.Parse(vsngaybd.Substring(6, 4)), int.Parse(vsngaybd.Substring(3, 2)), int.Parse(vsngaybd.Substring(0, 2)));
            }
            catch
            {
            }
            now = now.AddDays((double) num);
            DateTime time2 = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0x17, 0x3b, 0);
            return (now >= time2);
        }

        public string f_load_madangky()
        {
            //string vPathFileName = _pathFileKey + _fileNameKey+".exe";
            //string vPathFileNameNew = "";
            //vPathFileNameNew = Path.ChangeExtension(vPathFileName, "xml");
            try
            {
                
                //File.Move(vPathFileName, vPathFileNameNew);
            
                DataSet vdskeytmp = new DataSet();
                vdskeytmp = f_load_file(_fileNameKey);
                string vkey = vdskeytmp.Tables[0].Rows[0][1].ToString();
                //vkey = DecryptString(vkey, _mespass);
                //File.Move(vPathFileNameNew, vPathFileName);
                return vkey;
            }
            catch { return ""; }
            finally
            {
                
            }
            
        }
        public DataTable f_load_madangkyds()
        {
            DataSet set = new DataSet();
            set.Tables.Add();
            set.Tables[0].Columns.Add("1");
            set.Tables[0].Columns.Add("2");
            set.Tables[0].Columns.Add("3");
            set.Tables[0].Columns.Add("4");
            set.Tables[0].Columns.Add("5");
            set.Tables[0].Columns.Add("6");
            set.Tables[0].Columns.Add("7");
            set.Tables[0].Columns.Add("8");

            try
            {
                DataSet set2 = new DataSet();
                set2.ReadXml("abb.xml", XmlReadMode.ReadSchema);
                DataSet set3 = new DataSet();
                set3.ReadXml("xml//dskey.xml", XmlReadMode.ReadSchema);
                if (set2.Tables[0].Rows.Count > set3.Tables[0].Rows.Count)
                {
                    set = set2.Copy();
                }
                else
                {
                    set = set3.Copy();
                }
            }
            catch
            {
            }
            return set.Tables[0];
        }

        public void f_save_madangky(string key)
        {
            string str = this.EncryptString(key, _mespass);
            
            DataSet set = new DataSet();
            set.Tables.Add("tam");
            set.Tables[0].Columns.Add("yyy");
            set.Tables[0].Columns.Add("xxx");
            
            set.Tables[0].Rows.Add(new object[] { _idcomputer,str });
            f_save_file(set, _fileNameKey);
           
            
        }
        bool f_save_file(DataSet dstmp,string filename)
        {
            try
            {
                string vpath = _pathFileKey + filename + ".xml";
                dstmp.WriteXml(vpath, XmlWriteMode.WriteSchema);
                string vpathnew = Path.ChangeExtension(vpath, "exe");
                File.Move(vpath, vpathnew);
                return true;
            }
            catch { return false; }
        }
        DataSet f_load_file(string filename)
        {
            string vPathFileName = _pathFileKey + filename + ".exe";
            string vPathFileNameNew = "";
            vPathFileNameNew = Path.ChangeExtension(vPathFileName, "xml");
            try
            {

                File.Move(vPathFileName, vPathFileNameNew);

                DataSet vdskeytmp = new DataSet();
                vdskeytmp.ReadXml(vPathFileNameNew, XmlReadMode.ReadSchema);
                //string vkey = vdskeytmp.Tables[0].Rows[0][1].ToString();
                vdskeytmp.Tables[0].Rows[0][0] = DecryptString(vdskeytmp.Tables[0].Rows[0][0].ToString(), _mespass);
                vdskeytmp.Tables[0].Rows[0][1] = DecryptString(vdskeytmp.Tables[0].Rows[0][1].ToString(), _mespass);
                File.Move(vPathFileNameNew, vPathFileName);
                return vdskeytmp;
            }
            catch { return null; }
            finally
            {

            }
        }
        public void f_save_madangkyds(string maso, string madangky)
        {
            Class.Keys vkey = new Keys(madangky);
            DataTable table = this.f_load_madangkyds();
            table.Rows.Add(new object[] { maso, madangky, vkey.pNgayBatDauSuDung, vkey.pSoNgaySuDung
                , (vkey.pSoNgaySuDung == 999) ? 1 : 0, DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"), Environment.MachineName
                , DateTime.Now.ToString("yyyyMMdd") });
            DataSet set = new DataSet();
            set.Tables.Add(table.Copy());
            f_save_file(set, _fileNameKeyds);
            
        }

       
        
    }
}

